<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" show-icon :closable="false">
      </el-alert>
      <!-- 步骤条区域 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏区域 -->
      <!-- 外部包裹着一个表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-position="top"
        label-width="100px"
      >
        <el-tabs
          tabPosition="left"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联选择器 -->
              <!-- options指定数据源 -->
              <!-- 级联选择器v-model只接受数组 -->
              <el-cascader
                placeholder="请选择分类"
                clearable
                :options="cateList"
                :props="{
                  expandTrigger: 'hover',
                  label: 'cat_name',
                  value: 'cat_id',
                }"
                v-model="selectedKeys"
                @change="setGoods_cat"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in manyParams"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <!-- 渲染复选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(a, i) in item.attr_vals"
                  :key="i"
                  :label="a"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyParams"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片上传 -->
            <el-upload
              :action="uploadURL"
              :headers="headersObj"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handlesSccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <!-- 图片预览对话框 -->
            <el-dialog
              title="图片预览"
              :visible.sync="previewPicDialogVisible"
              width="50%"
            >
              <el-image
                :src="previewPath"
                fit="contain"
                class="previewImg"
              ></el-image>
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="butAdd" @click="addGoods"
              >添加商品
            </el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 步骤条激活索引值
      activeIndex: 0,
      // 已激活的步骤条
      activeIndexs: ['0'],
      // 添加商品表单数据对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: '',
        // 图片数组
        pics: [],
        // 商品描述
        goods_introduce: '',
        // 属性数组
        attrs: []
      },
      // 分类数据
      cateList: [],
      // 选中分类的key值集合
      selectedKeys: [],
      // 添加商品表单验证对象
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择分类', trigger: 'blur' }
        ]
      },
      // 动态参数数据
      manyParams: [],
      // 静态属性数据
      onlyParams: [],
      // 图片上传地址
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览URL
      previewPath: '',
      // 图片预览对话框开关
      previewPicDialogVisible: false
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取分类数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类列表失败！')
      }
      this.cateList = res.data
      this.$message.success('获取分类列表成功！')
    },
    // 监听级联选择器，选中项发生改变时保存选中的分类
    setGoods_cat () {
      console.log(this.selectedKeys)
      // 判断是否是第三级分类
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.addForm.goods_cat = ''
        return
      }
      this.addForm.goods_cat = this.selectedKeys.length > 0 ? this.selectedKeys.join(',') : ''
      console.log(this.addForm.goods_cat)
    },
    // 标签页切换前触发事件
    beforeTabLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.selectedKeys.length !== 3) {
        this.$message.error('请选择分类')
        return false
      }
      return true
    },
    // 标签页点击事件
    tabClicked () {
      console.log(this.activeIndex)
      console.log(this.activeIndexs)
      console.log(this.isNewActiveIndex)
      if (this.activeIndex === '1') {
        this.getParams(this.cateId, 'many')
      } else if (this.activeIndex === '2') {
        this.getParams(this.cateId, 'only')
      }
      if (this.isNewActiveIndex) {
        this.activeIndexs.push(this.activeIndex)
      }
    },
    // 获取参数数据
    async getParams (cateId, sel) {
      const { data: res } = await this.$http.get('categories/' + cateId + '/attributes', {
        params: { sel: sel }
      })
      console.log(res)
      if (sel === 'many') {
        this.manyParams = res.data
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        })
      } else {
        this.onlyParams = res.data
      }
      if (res.meta.status !== 200) { return this.$message.error('获取分类参数失败！') }
    },
    // 处理图片预览事件
    handlePreview (file) {
      console.log(file)
      this.previewPath = file.response.data.url
      console.log(this.previewPath)
      this.previewPicDialogVisible = true
    },
    // 处理图片移除事件
    handleRemove (file) {
      console.log(file)
      const filePath = file.response.data.tmp_path
      const i = this.addForm.pics.findIndex(x => x.pic === filePath)
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm)
    },
    // 上传成功后调用
    handlesSccess (res) {
      const pic = { 'pic': res.data.tmp_path }
      this.addForm.pics.push(pic)
      console.log(this.addForm)
    },
    // 提交添加商品表单
    addGoods () {
      console.log(this.addForm)
      console.log(this.manyParams)
      console.log(this.onlyParams)
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) { return this.$message.error('表单校验未通过，请填写必填项') }
        // 动态添加参数
        // 表单校验通过，发起网络请求
        // 可用 lodash cloneDeep(obj) 对象深拷贝
        // 处理动态参数与静态属性
        this.manyParams.forEach(item => {
          const newObj = { attr_id: item.attr_id, attr_value: item.attr_vals.join(',') }
          this.addForm.attrs.push(newObj)
        })
        this.onlyParams.forEach(item => {
          const newObj = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.addForm.attrs.push(newObj)
        })
        console.log(this.addForm)
        // 发起网络请求
        const { data: res } = await this.$http.post('goods', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) { return this.$message.error('添加商品失败') }
        this.$message.success('添加商品成功！')
        // 清空已激活的步骤条
        this.activeIndexs = ['0']
        // 跳转至商品列表
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    // 当前选中的三级分类id
    cateId () {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    // 判断当前标签页是否第一次激活
    isNewActiveIndex () {
      const act = this.activeIndexs.indexOf(this.activeIndex)
      return act === -1
    }
  }
}
</script>
<style lang="less" scoped>
.el-cascader {
  width: 100%;
}
.el-checkbox {
  margin: 0 15px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.butAdd {
  margin: 15px 0;
  float: right;
}
</style>
